package com.sky.Task;


import cn.hutool.core.util.ObjectUtil;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

//    @Scheduled(cron = "0 0/1 * * * ?")
//    public void disposeTimeoutUnpayOrders(){
//        log.info("定时任务：清理超时未支付订单");
//        //1、查询出所有超时未支付的订单([15分钟前]下的单，并且现在的[订单状态]还是[待支付]的)
//        List<Orders> ordersList = orderMapper.queryByOrderTimeAndStatus(date, Orders.PENDING_PAYMENT);
//
//        //2、判断有没有此类订单，如果没有，直接结束
//        if (ObjectUtil.isEmpty(ordersList)){
//            return;
//        }
//
//        ordersList.forEach(orders -> {
//            orders.setStatus(Orders.CANCELLED);
//            orders.setCancelTime(LocalDateTime.now());
//            orders.setCancelReason("订单超时未支付");
//            orderMapper.update(orders);
//        });
//
//        //3、如果有此类订单，修改订单状态为[已取消]、订单取消时间、订单取消原因
//       Orders.builder()
//               .status(Orders.CANCELLED)
//               .cancelTime(LocalDateTime.now())
//               .build();
//    }

    @Scheduled(cron = "0 * * * * ?")//每秒执行一次
    public void processTimeoutOrder(){
        log.info("定时任务：处理超时订单",LocalDateTime.now());

        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);

        List<Orders> ordersList = orderMapper.queryByOrderTimeAndStatus(Orders.PENDING_PAYMENT,time);

        if (ordersList!=null && ordersList.size()>0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时,未支付，自动取消");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }

    }

    @Scheduled(cron = "0 0 1 * * ?")//每天凌晨1点执行一次
    public void processDeliveryOrder(){
        log.info("定时任务：处理派送中的订单",LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);

        List<Orders> ordersList = orderMapper.queryByOrderTimeAndStatus(Orders.PENDING_PAYMENT,time);

        if (ordersList!=null && ordersList.size()>0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }
}
